package com.tssup.fesco.common.frame.common;


import java.util.stream.Stream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;

import com.tssup.fesco.common.utils.json.JsonUtil;
import com.tssup.fesco.common.vo.Context;
import com.tssup.fesco.common.vo.OperatorVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 公共基础Controller
 *
 * @author Administrator
 * @date 2016年7月8日
 * @see
 */
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String CODE = "code";
    private static final String MESSAGE = "msg";



    protected DefaultWebApiResult success() {
        return DefaultWebApiResult.success();
    }

    protected DefaultWebApiResult success(Object data) {
        return DefaultWebApiResult.success(data);
    }

    protected DefaultWebApiResult failure(String errCode, String errMsg) {
        return new DefaultWebApiResult(errMsg, errCode);
    }


    /**
     * @param errCode   错误码
     * @param errMsg    错误信息
     * @param ex        异常, 输出到日志
     * @param reqParams 请求参数, 转换成JSON格式, 并输出到日志
     * @return
     */
    protected DefaultWebApiResult failure(String errCode, String errMsg, Throwable ex, Object... reqParams) {
        if (StringUtils.isEmpty(errCode)){
            errCode = "-1";
        }
        if (StringUtils.isEmpty(errMsg)){
            errMsg = "系统异常";
        }
        logger.error("[errCode: {}, errMsg: {}, reqParams: {}]", errCode, errMsg, JsonUtil.toJson(reqParams), ex);

        return new DefaultWebApiResult(errMsg, errCode);
    }

    /**
     * @param errCode   错误码
     * @param errMsg    错误信息
     * @param ex        异常, 输出到日志
     * @param reqParams 请求参数, 转换成JSON格式, 并输出到日志
     * @return
     */
    protected DefaultWebApiResult failure(String errCode, String errMsg, Object o, Throwable ex, Object... reqParams) {
        if (StringUtils.isEmpty(errCode)){
            errCode = "-1";
        }
        if (StringUtils.isEmpty(errMsg)){
            errMsg = "系统异常";
        }
        logger.error("[errCode: {}, errMsg: {}, reqParams: {}]", errCode, errMsg, JsonUtil.toJson(reqParams), ex);

        return new DefaultWebApiResult(errCode, errMsg, o);
    }

    /**
     * 转换统一响应结果
     *
     * @param retCode     错误码
     * @param retMsg      错误信息
     * @param resultKey   响应结果内容key
     * @param resultValue 响应结果内容
     * @return
     */
    protected String toJSONString(String retCode, String retMsg, String resultKey, Object resultValue) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNoneEmpty(resultKey)) {
            jsonObject.put(resultKey, resultValue);
        }
        if (StringUtils.isNoneEmpty(retCode)) {
            jsonObject.put(CODE, retCode);
        }
        if (StringUtils.isNoneEmpty(retMsg)) {
            jsonObject.put(MESSAGE, retMsg);
        }
        return jsonObject.toJSONString();
    }
    
    protected void needLog() {
        
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length == 0) {
            throw new RuntimeException("登录信息丢失，请重新登录");
        }
        OperatorVo vo = new OperatorVo();
        Stream.of(cookies).forEach(cookie -> {
            logger.debug("Current Cookie:" + cookie.getName() + ":" + cookie.getValue());
            if("userId".equals(cookie.getName())) {
                vo.setOperator(Integer.parseInt(cookie.getValue()));
            } else if ("userRealName".equals(cookie.getName())) {
                vo.setOperaterName(unescape(unescape(cookie.getValue())));
            }
        });
        Context.setOperator(vo);
    }

    /**
     * escape 解码
     * @param src
     * @return
     */
    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }
}
